<?php
/**
 * Created by PhpStorm.
 * User: 17208
 * Date: 2019/6/13
 * Time: 11:20
 */

namespace app\common\lib;
use think\Container;

class WebSocketToken
{
    /** @var string user_id & fd 绑定保存的key  */
    private $web_socket_tokens_key = "web_socket_tokens";
    /** 通过user_id 获取 fd */
    public function get_fd($user_id){
        $data = Redis::get($this->web_socket_tokens_key);
        $data = json_decode($data,true)?json_decode($data,true):[];
        $fd = array_search($user_id,$data);
        return $fd;
    }
    /** 通过 fd  获取 user_id  */
    public function get_user_id($fd){
        $data = Redis::get($this->web_socket_tokens_key);
        $data = json_decode($data,true)?json_decode($data,true):[];
        return isset($data[$fd])?$data[$fd]:false;
    }
    /** 获取token 信息 (user_id) */
    public function get($token){
        return  Redis::get($token);
    }
    /** 保存token */
    public function set($user_id){
        $token = $this->get_key($user_id);
        Redis::set($token,$user_id,2*60*60);
        return $token;
    }
    /** 绑定fd */
    public function bind_fd($user_id,$fd){
        if($user_id && $fd){
            $data = Redis::get($this->web_socket_tokens_key);
            $data = json_decode($data,true);
            if($data){
                $index = array_search($user_id,$data);
                if($index !==false ) unset($data[$index]);
                $data[$fd] = $user_id;
            }else{
                $data = [
                    $fd=>$user_id
                ];
            }
            Redis::set($this->web_socket_tokens_key,json_encode($data));
            return true;
        }else{
            return false;
        }
    }
    /** 检验fd是否存在 */
    public function exist($fd){
        return Container::get('swoole')->exist($fd);
    }
    /** token保存规则 */
    public function get_key($user_id){
        return md5("websocket_token_{$user_id}_".uniqid());
    }

}